import Vue from 'vue'
import VueRouter from 'vue-router'

// 全局前置守卫 先导包
import store from '@/store/index.js'

// 导入登录注册组件
import Register from '@/views/Register/index.vue'
import Login from '@/views/Login/index.vue'

// 导入 404 组件
import _404 from '@/views/404/index.vue'
// 导入 Home 组件
import Home from '@/views/Layout/Home/index.vue'
// 导入 User 组件
import UserInfo from '@/views/Layout/User/UserInfo.vue'

// 导入 UserPwd 修改密码组件
import UserPwd from '@/views/Layout/User/UserPwd.vue'

// 导入更换头像组件
import UserAvatar from '@/views/Layout/User/UserAvatar.vue'
// 文章分类
import ArtCate from '@/views/Layout/Article/ArtCate.vue'
// 文章列表
import ArtList from '@/views/Layout/Article/ArtList.vue'
import Layout from '@/views/Layout/index.vue'
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: Layout,
    redirect: '/home', // 路由重定向
    children: [
      // 嵌套路由
      { path: 'home', component: Home },
      // 用户信息
      { path: 'user-info', component: UserInfo },
      // 上传头像
      { path: 'user-avatar', component: UserAvatar },
      // 重置密码的子路由规则
      { path: 'user-pwd', component: UserPwd },
      // 文章分类
      { path: 'art-cate', component: ArtCate },
      // 文章列表
      { path: 'art-list', component: ArtList }

    ]
  },
  // 配置404
  { path: '*', component: _404 }

]

const router = new VueRouter({
  routes
})
// 准备一个白名单数组，这里写的路由是不需要token 就可访问的
const whiteList = ['/login', '/register']

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 1.获取token
  const { token } = store.state.user
  // 判断有没有token
  if (token) {
    next()
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      // 想要去首页，先登录
      next()
    } else {
      next('/login')
    }
  }
})
export default router
